package com.leo.demo.service.impl;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.leo.demo.model.UserInfo;
import com.leo.demo.service.UserInfoService;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: UserInfoServiceImpl
 * @Description: 简单的增删改查
 * @Author: leo825
 * @Date: 2020-01-02 11:24
 * @Version: 1.0
 */
@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @PostConstruct
    public void init()
    {
        try
        {
            Resource resource = new ClassPathResource("/tables/user_info.sql");
            String sqlText = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
            log.info("SQL = {}", sqlText);
            Arrays.stream(sqlText.split(";")).filter(StringUtils::isNotBlank).forEach(jdbcTemplate::execute);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    @Override
    public void insertUserInfo(UserInfo userInfo)
    {
        jdbcTemplate.execute("INSERT INTO USER_INFO(NAME,GENDER,AGE,REMARKS) VALUES('" + userInfo.getName() + "','" + userInfo.getGender() + "','" + userInfo.getAge() + "','" + userInfo.getRemarks() + "')");
    }
    
    @Override
    public void deleteUserInfo(Integer id)
    {
        jdbcTemplate.execute("DELETE FROM USER_INFO WHERE ID = " + id);
    }
    
    @Override
    public void updateUserInfo(Integer id, UserInfo newUserInfo)
    {
        jdbcTemplate.update("UPDATE USER_INFO SET NAME=?, GENDER=?, AGE=? ,REMARKS=? WHERE ID=?", new Object[] {newUserInfo.getName(), newUserInfo.getGender(), newUserInfo.getAge(), newUserInfo.getRemarks(), id});
    }
    
    @Override
    public List<UserInfo> getUserInfoList()
    {
        List<UserInfo> userInfos = new ArrayList<>();
        List<Map<String, Object>> results = jdbcTemplate.queryForList("SELECT * FROM USER_INFO");
        for (Map obj : results)
        {
            UserInfo userInfo = new UserInfo();
            userInfo.setId((Integer)obj.get("ID"));
            userInfo.setName((String)obj.get("NAME"));
            userInfo.setGender("0".equals(obj.get("GENDER")) ? "女" : "男");
            userInfo.setAge((String)obj.get("AGE"));
            userInfo.setRemarks((String)obj.get("REMARKS"));
            userInfos.add(userInfo);
        }
        return userInfos;
    }
}
